package utils

import (
	"log"
	"net/http"
	"os"
	"strconv"
	"strings"
)

func RabbitServer() string {
	s, ok := os.LookupEnv("RABBITMQ_SERVER")
	if !ok {
		panic("RABBITMQ_SERVER not set")
	}
	return s
}

func ServerAddr() string {
	addr, ok := os.LookupEnv("LISTEN_ADDR")
	if ok {
		return addr
	}
	return "127.0.0.1:12345"
}

func ObjectRoot() string {
	dir, ok := os.LookupEnv("STORAGE_ROOT")
	if ok {
		return dir
	}
	return "/tmp/"
}

func ObjectPath() string {
	return "/objects/"
}

func GetObjectName(r *http.Request) string {
	return strings.Split(r.URL.EscapedPath(), "/")[2]
}

func GetObject(r *http.Request) string {
	return ObjectRoot() + ObjectPath() + GetObjectName(r)
}

func LocatePath() string {
	return "/locate/"
}

func ApiServerName() string {
	return "apiServers"
}

func DataServerName() string {
	return "dataServers"
}

func EsServer() string {
	s, ok := os.LookupEnv("ES_SERVER")
	if !ok {
		panic("ES_SERVER not set")
	}
	return s
}

func VersionPath() string {
	return "/versions/"
}

func GetHashFromHeader(h http.Header) string {
	digest := h.Get("digest")
	if len(digest) < 9 {
		return ""
	}

	if digest[:8] != "SHA-256" {
		return ""
	}

	return digest[8:]
}

func GetSizeFromHeader(h http.Header) int64 {
	size, err := strconv.ParseInt(h.Get("content-length"), 0, 64)
	if err != nil {
		log.Println("Parse size error", err)
		return -1
	}
	return size
}
